package logic

import (
	"iot-base/auth/model"
	"iot-base/auth/svc"
	"strconv"
	"strings"
)

type GroupLogic struct {
}

func NewGroupLogic() *GroupLogic {
	return &GroupLogic{}
}

// AddGroup 添加权限组.
func (l *GroupLogic) AddGroup(pid int64, name string) (int64, error) {
	var group model.AuthGroup
	group.Pid = pid
	group.GroupName = name
	if pid != 0 {
		// 查询上级的path
		pGroup, err := svc.Dao.TAuthGroup.GetGroupsByid(pid)
		if err != nil {
			return 0, err
		}
		group.Path = strings.Trim(pGroup.Path+"/"+strconv.FormatInt(pid, 10), "/")
	}
	err := svc.Dao.TAuthGroup.AddGroup(&group)
	return group.ID, err
}

// DelGroup 添加权限组.
func (l *GroupLogic) DelGroup(id int64) (int64, error) {
	return svc.Dao.TAuthGroup.DelGroup(id)
}

// EditGroup 修改组.
func (l *GroupLogic) EditGroup(id, pid int64, name string, rules []int64) (int64, error) {
	var path string
	if pid != 0 {
		// 查询上级的path
		pGroup, err := svc.Dao.TAuthGroup.GetGroupsByid(pid)
		if err != nil {
			return 0, err
		}
		path = strings.Trim(pGroup.Path+"/"+strconv.FormatInt(pid, 10), "/")
	}
	return svc.Dao.TAuthGroup.UpdateGroup(id, pid, name, path)
}

func (l *GroupLogic) FindGroup(page int, size int) ([]model.AuthGroup, error) {
	return svc.Dao.TAuthGroup.FindGroup(page, size)
}

func (l *GroupLogic) FindGroupCount() (int64, error) {
	return svc.Dao.TAuthGroup.FindGroupCount()
}

func (l *GroupLogic) FindAll() ([]model.AuthGroup, error) {
	return svc.Dao.TAuthGroup.FindAll()
}

// GetChildrenGroupIds 取出当前管理员所拥有权限的分组.
func (l *GroupLogic) GetChildrenGroupIds(uid int64) ([]groupItem, error) {
	// 取出当前管理的分组.
	groups, err := svc.Dao.TAuthGroup.GetUserGroup(uid)
	if err != nil {
		return nil, err
	}
	groupAll := make([]model.AuthGroup, 0, 1)
	path := groups[0].Path
	if groups[0].Pid == 0 {
		path = strconv.FormatInt(groups[0].ID, 10)
	}
	// 取出所有分组
	groupNode, err := svc.Dao.TAuthGroup.FindChildNode(path)
	groupAll = append(groupAll, groupNode...)
	groupAll = append(groupAll, groups...)
	ml := groupList(groupAll)
	ret := ml.processToTree(0, 0)
	return ret, nil
}

type groupList []model.AuthGroup

type groupItem struct {
	model.AuthGroup
	Child []groupItem `json:"child"`
}

func (m *groupList) processToTree(pid int64, level int64) []groupItem {
	var groupTree []groupItem
	if level == 10 {
		return groupTree
	}
	list := m.findChildren(pid)
	if len(list) == 0 {
		return groupTree
	}
	for _, v := range list {
		child := m.processToTree(v.ID, level+1)
		groupTree = append(groupTree, groupItem{v, child})

	}

	return groupTree
}

func (m *groupList) findChildren(pid int64) []model.AuthGroup {
	var child []model.AuthGroup
	for _, v := range *m {
		if v.Pid == pid {
			child = append(child, v)
		}
	}
	return child
}
